/*
    Stompfest AdViewer
    Copyright (C) MMX Ron Rebennack

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.navigateToURL;
import flash.utils.Timer;
import mx.containers.Canvas;
import mx.controls.TextArea;
import mx.core.Application;
import mx.styles.StyleManager;
import mx.utils.ObjectUtil;
import mx.effects.easing.Bounce;


private var xA_Data:Array;
private var xT_Main:Timer;
private var xPlaying:Boolean = true;

[Embed(source="/images/Nav_Play.png")]
private var IM_Play:Class;

[Embed(source="/images/Nav_Pause.png")]
private var IM_Pause:Class;

private var xA_Set:Array;
private var xConfig:String;
private var xTextAlpha:Number;
private var xTextColor:uint;
private var xTextBGColor:uint;

private function Init():void
    {
    xA_Set = new Array();
    xA_Data = new Array();

    xTextAlpha = .4;
    xTextColor = 0x000000;
    xTextBGColor = 0xffffff;

    xConfig = Application.application.parameters.ConfigFile;
    if ( xConfig == null )
        {
        ShowError("Missing Configuration file (XML) " + ObjectUtil.toString(Application.application.parameters));
        return;
        }

    LoadSettings();
    }

private function LoadSettings():void
    {
    try
        {
        var xUL:URLLoader = new URLLoader(new URLRequest(xConfig));

        xUL.addEventListener(Event.COMPLETE, EV_XMLReady, false, 0, true);
        xUL.addEventListener(IOErrorEvent.IO_ERROR, EV_XMLError, false, 0, true);
        }
    catch ( xError:Error )
        {
        ShowError(xError.message);
        }
    }

private function EV_XMLError(iEvt:IOErrorEvent):void
    {
    ShowError("IOError: " + iEvt.text + " --> " + xConfig);
    }

private function ShowError(iMessage:String = null):void
    {
    xIN_Error.text = iMessage;
    xVS_Pos.enabled = false;
    xC_Error.visible = true;
    xIM_Action.enabled = false;
    }

private function EV_XMLReady(iEvent:Event):void
    {
    var xXML:XMLList;

    try
        {
        var xUL:URLLoader = URLLoader(iEvent.target);

        xXML = XMLList(xUL.data);
        }
    catch ( xError:Error )
        {
        ShowError(xError.message);
        return;
        }

    if ( xXML == null )
        return;

    var xAtt:XML;
    var xBaby:XML;
    var xBase:XML;
    var xO_Item:Object;
    var xA_Images:Array = new Array();

    for each ( xBase in xXML.children() )
        {
        for each ( xBaby in xBase.children() )
            {
            if ( xBase.name() == "Settings" )
                {
                xA_Set[xBaby.name().toString()] = xBaby.valueOf().toString();
                }

            if ( xBase.name() == "Images" )
                {
                xO_Item = new Object();

                for each ( xAtt in xBaby.attributes() )
                    {
                    xO_Item[xAtt.name().toString()] = xAtt.valueOf().toString();
                    }

                xA_Images.push(xO_Item);
                }
            }
        }

    DoTextAlpha();
    DoTextColor();
    DoTextBGColor();
    DoBackgroundColor();

    xT_Main = new Timer(int(GetSetting("Delay", 2000)));

    xVS_Main.removeAllChildren();

    for each ( xO_Item in xA_Images )
        {
        AddMyItem(xO_Item["Desc"], xO_Item["URL"], xO_Item["Link"]);
        }

    xVS_Pos.maximum = (xA_Data.length - 1);

    xT_Main.start();
    xT_Main.addEventListener(TimerEvent.TIMER, xT_Main_Tick, false, 0, true);
    }

private function DoTextColor():void
    {
    if ( xA_Set["TextColor"] == null || xA_Set["TextColor"] == "" )
        return;

    var xNewColor:uint = StyleManager.getColorName(xA_Set["TextColor"]);

    if ( xNewColor != StyleManager.NOT_A_COLOR )
        {
        xTextColor = xNewColor;
        }
    }

private function DoTextBGColor():void
    {
    if ( xA_Set["TextBGColor"] == null || xA_Set["TextBGColor"] == "" )
        return;

    var xNewColor:uint = StyleManager.getColorName(xA_Set["TextBGColor"]);

    if ( xNewColor != StyleManager.NOT_A_COLOR )
        {
        xTextBGColor = xNewColor;
        }
    }

private function DoTextAlpha():void
    {
    if ( xA_Set["TextAlpha"] == null || xA_Set["TextAlpha"] == "" )
        return;

    if ( isNaN(int(xA_Set["TextAlpha"])) == false )
        {
        xTextAlpha = Number(xA_Set["TextAlpha"]);
        }
    }

private function DoBackgroundColor():void
    {
    if ( xA_Set["BGColor"] == null || xA_Set["BGColor"] == "" )
        {
        this.setStyle("backgroundAlpha", 0);
        this.setStyle("backgroundColor", null);
        return;
        }

    var xColor:String = xA_Set["BGColor"];
    var xNewColor:uint;

    if ( xColor.indexOf(",") > 0 )
        {
        var xA_Colors:Array = xColor.split(",");
        var xA_NewColors:Array = new Array();

        xNewColor = StyleManager.getColorName(xA_Colors[0]);
        if ( xNewColor != StyleManager.NOT_A_COLOR )
            xA_NewColors.push(xNewColor);

        xNewColor = StyleManager.getColorName(xA_Colors[1]);
        if ( xNewColor != StyleManager.NOT_A_COLOR )
            xA_NewColors.push(xNewColor);

        this.setStyle("backgroundAlpha", 1);
        this.setStyle("backgroundGradientColors", xA_NewColors);
        }
    else
        {
        xNewColor = StyleManager.getColorName(xColor);

        if ( xNewColor != StyleManager.NOT_A_COLOR )
            {
            this.setStyle("backgroundAlpha", 1);
            this.setStyle("backgroundColor", xNewColor);
            }
        }
    }

private function GetSetting(iSet:String, iDefault:Object = null):Object
    {
    if ( xA_Set[iSet] == null || xA_Set[iSet] == "" )
        return iDefault;

    return xA_Set[iSet];
    }

private function AddMyItem(iText:String, iURLImage:String, iURLLink:String):void
    {
    var xO_Temp:Object = new Object();

    xO_Temp.Text = iText;
    xO_Temp.URLLink = iURLLink;
    xO_Temp.URLImage = iURLImage;
    xA_Data.push(xO_Temp);

    var xC_Dude:Canvas = new Canvas();
    var xTA_Text:TextArea = new TextArea();

    xC_Dude.setStyle("showEffect", xE_FadeIn);
    xC_Dude.setStyle("hideEffect", xE_ZoomOut);
    xC_Dude.setStyle("backgroundImage", iURLImage);

    xC_Dude.id = iText;
    xC_Dude.cacheAsBitmap = true;
    xC_Dude.verticalScrollPolicy = "off";
    xC_Dude.horizontalScrollPolicy = "off";

    if ( iURLLink != null && iURLLink != "" )
        {
        xC_Dude.buttonMode = true;
        xC_Dude.useHandCursor = true;

        xC_Dude.addEventListener(MouseEvent.CLICK, EV_LinkClick, false, 0, true);
        }

    xTA_Text.text = iText;
    xTA_Text.height = 40;
    xTA_Text.styleName = "PicText";
    xTA_Text.percentWidth = 100;

    xTA_Text.setStyle("top", (xVS_Main.height - xTA_Text.height) - 2);
    xTA_Text.setStyle("color", xTextColor);
    xTA_Text.setStyle("backgroundAlpha", xTextAlpha);
    xTA_Text.setStyle("backgroundColor", xTextBGColor);

    xC_Dude.addChild(xTA_Text);
    xVS_Main.addChild(xC_Dude);
    }

private function EV_LinkClick(iEvt:MouseEvent):void
    {
    navigateToURL(new URLRequest(xA_Data[xVS_Pos.value].URLLink), "_blank");
    }

private function xVS_Pos_Change(iEvent:Event):void
    {
    xVS_Main.selectedIndex = xVS_Pos.value;

    if ( xPlaying )
        DoAction(false);
    }

private function xT_Main_Tick(iEvent:TimerEvent):void
    {
    var xNext:int = xVS_Main.selectedIndex + 1;

    if ( xNext >= xVS_Main.numChildren )
        xNext = 0;

    xVS_Pos.value = xNext;
    xVS_Main.selectedIndex = xNext;
    }

private function xIM_Action_Click(iEvent:MouseEvent):void
    {
    DoAction(!xPlaying);
    }

private function DoAction(iPlay:Boolean):void
    {
    if ( iPlay )
        {
        xT_Main.start();
        xT_Main_Tick(null);

        xIM_Action.source = IM_Pause;
        xIM_Action.toolTip = "Pause";
        }
    else
        {
        xT_Main.stop();
        xIM_Action.source = IM_Play;
        xIM_Action.toolTip = "Play";
        }

    xPlaying = iPlay;
    }

private function FormatToolTip(iItem:Object):String
    {
    return xA_Data[iItem].Text;
    }
